#!/usr/bin/python

import optparse
import sys

import tables

import charmicat


def main():
    """
    ccat_setattr.py [opts] ATTR VALUE file1.h5 [file2.h5 [...]]

    Sets table attribute ATTR to value VALUE in each input file.
    """

    op = optparse.OptionParser(usage=main.__doc__)

    opts, args = op.parse_args()
    
    if len(args) < 3:
        msg = "Please supply the name of the attribute, its desired value, and at least one input file."
        raise charmicat.BadCommandLineError(msg, -1)

    name = args.pop(0)
    value = args.pop(0)

    for ip, path in enumerate(args):
        sys.stdout.write("{0}/{1} files complete\r".format(ip, len(args)))
        sys.stdout.flush()
                         
        fp = tables.openFile(path, 'r+')

        fp.root.nt.attrs[name] = value

        fp.close()

    
    print "{0}/{0} files complete\r".format(len(args))

if __name__ == "__main__":
    try:
        sys.exit(main())
    except charmicat.BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
